package server.dao;

import common.messages.HistoryMessage;
import common.messages.GroupChatMessage;
import common.messages.PrivateChatMessage;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    public void savePrivateMessage(PrivateChatMessage message) {
        String sql = "INSERT INTO private_message (send_id, receive_id, message, sender_name, receiver_name, file_name, message_type) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = SQLConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, message.getSenderId());
            pstmt.setInt(2, message.getReceiverId());
            pstmt.setString(3, message.getMessage());
            pstmt.setString(4, message.getSenderName());
            pstmt.setString(5, message.getReceiverName());
            pstmt.setString(6, message.getFileName());
            pstmt.setString(7, message.getMessageType());


            int affectedRows = pstmt.executeUpdate();

            if (affectedRows == 0) {
                throw new SQLException("插入私聊消息失败，影响行数为 0");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void saveGroupMessage(GroupChatMessage message) {
        String sql = "INSERT INTO group_message (send_id, group_id, message, sender_name, group_name , file_name, message_type ) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = SQLConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {


            pstmt.setInt(1, message.getSenderId());
            pstmt.setInt(2, message.getGroupId());
            pstmt.setString(3, message.getMessage());
            pstmt.setString(4, message.getSenderName());
            pstmt.setString(5, message.getGroupName());
            pstmt.setString(6, message.getFileName());
            pstmt.setString(7, message.getMessageType());

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows == 0) {
                throw new SQLException("插入群消息失败，影响行数为0");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<HistoryMessage> getPrivateMessages(Integer userId, Integer friendId) {
        String sql = "SELECT * FROM private_message " +
                "WHERE (send_id = ? AND receive_id = ?) OR (send_id = ? AND receive_id = ?) " +
                "ORDER BY send_time ASC";

        List<HistoryMessage> messages = new ArrayList<>();

        try (Connection conn = SQLConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            pstmt.setInt(2, friendId);
            pstmt.setInt(3, friendId);
            pstmt.setInt(4, userId);

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    HistoryMessage message = new HistoryMessage();

                    message.setSenderName(rs.getString("sender_name"));
                    message.setMessage(rs.getString("message"));

                    Timestamp timestamp = rs.getTimestamp("send_time");
                    if (timestamp != null) {
                        message.setSendTime(timestamp.toLocalDateTime());
                    }
                    message.setMessageType(rs.getString("message_type"));
                    message.setFileName(rs.getString("file_name"));

                    messages.add(message);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取私聊消息失败", e);
        }

        return messages;
    }


    public List<HistoryMessage> getGroupMessages(Integer groupId) {
        String sql = "select * from group_message where group_id = ? ";
        List<HistoryMessage> messages = null;
        try (Connection conn = SQLConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, groupId);

            try (ResultSet rs = pstmt.executeQuery()) {
                messages = new ArrayList<>();
                while (rs.next()) {
                    HistoryMessage message = new HistoryMessage();
                    message.setSenderName(rs.getString("sender_name"));
                    message.setMessage(rs.getString("message"));

                    Timestamp timestamp = rs.getTimestamp("send_time");
                    if (timestamp != null) {
                        message.setSendTime(timestamp.toLocalDateTime());
                    }
                    message.setMessageType(rs.getString("message_type"));
                    message.setFileName(rs.getString("file_name"));
                    messages.add(message);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取群聊消息失败", e);
        }

        return messages;
    }
}
